package com.ba.base.utils

import android.annotation.SuppressLint
import android.app.Activity
import android.content.pm.ActivityInfo
import android.graphics.Color
import android.util.DisplayMetrics
import android.util.TypedValue
import android.view.View
import android.view.WindowManager.LayoutParams.*
import android.widget.TextView


object DisplayUtils {

    fun autoMatchFont(view: TextView) {
        view.addOnLayoutChangeListener { v, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom ->
            val vWidth = v.width.toFloat()
            val paint = view.paint
            val text = view.text.toString()
            val textLen = paint.measureText(text)
            val oldSize = view.textSize
            if (textLen != vWidth) {
                val size = vWidth * oldSize / textLen
                view.setTextSize(TypedValue.COMPLEX_UNIT_PX, size)
            }
        }
    }

    fun screen(activity: Activity): FloatArray {
        val outMetrics = DisplayMetrics()
        activity.windowManager.defaultDisplay.getMetrics(outMetrics)
        val width = outMetrics.widthPixels
        val height = outMetrics.heightPixels
        val density = outMetrics.density
        // 屏幕宽度(dp)
        val screenWidth: Float = width / density
        // 屏幕高度(dp)
        val screenHeight = height / density

        return floatArrayOf(screenWidth, screenHeight)
    }

    @SuppressLint("SourceLockedOrientationActivity")
    fun changeFullView(fullscreen: Boolean, activity: Activity) {
        if (fullscreen) {
            val attrs = activity.window.attributes
            attrs.flags = attrs.flags or FLAG_FULLSCREEN
            attrs.flags = attrs.flags or FLAG_KEEP_SCREEN_ON
            activity.window.attributes = attrs
            activity.window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LOW_PROFILE
            activity.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
            activity.window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_VISIBLE

            ThemeHelper.setColor(activity, Color.BLACK)
        } else {
            val attrs = activity.window.attributes
            attrs.flags = attrs.flags and FLAG_FULLSCREEN.inv()
            attrs.flags = attrs.flags and FLAG_KEEP_SCREEN_ON.inv()
            activity.window.attributes = attrs
            activity.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
            activity.window.setFlags(FLAG_LAYOUT_IN_SCREEN, FLAG_LAYOUT_IN_SCREEN)

            ThemeHelper.setColor(activity, SharedPreUtils.getTheme(activity))
        }
    }
}